package com.bsoft.exchange.controller.charge;

import com.bsoft.exchange.config.dozer.DozerUtils;
import com.bsoft.exchange.domain.*;
import com.bsoft.exchange.pojo.*;
import com.bsoft.exchange.response.ResponseEntity;
import com.bsoft.exchange.service.CreateOrderNoService;
import com.bsoft.exchange.service.PatientService;
import com.bsoft.exchange.service.PaymentService;
import com.bsoft.exchange.util.BaseResponse;
import com.bsoft.exchange.util.Constant;
import com.bsoft.exchange.vo.MachiningHerbalMedCostVo;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 创建日期:2019/06/12
 * 创建人: 赵太行
 * 支付方面的接口
 */
@RestController
public class PaymentController {

    private static final Logger log = LoggerFactory.getLogger(PaymentController.class);

    @Autowired
    PaymentService paymentService;
    @Autowired
    Mapper dozerMapper;
    @Autowired
    PatientService patientService;
    private BaseResponse<List<UnPayedListDomain>> unPayedListDomain;

    private BaseResponse<DrugDomain> drugDomain;


    @Autowired
    CreateOrderNoService createOrderNoService;
    /**
     * 获取待支付接口
     * @param unPayedPojo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUnpayedList",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<List<UnPayedListDomain>> getUnpayedList(@RequestBody UnPayedPojo unPayedPojo){
        ResponseEntity<List<UnPayedListDomain>>unPayedListEntity=new ResponseEntity<>();
        try {
            unPayedListDomain = paymentService.getUnPayedListService(unPayedPojo);
        } catch (SQLException e) {
            e.printStackTrace();
            unPayedListEntity.setCode(Constant.errorTag);
            unPayedListEntity.setMessage("数据库查询失败");
            return unPayedListEntity;
        }

        if (unPayedListDomain.getCode()==Constant.errorTag){
            unPayedListEntity.setCode(Constant.errorTag);
            unPayedListEntity.setMessage(unPayedListDomain.getMessage());
            return unPayedListEntity;
        }

        unPayedListEntity.setCode(Constant.successResponse);
        unPayedListEntity.setMessage("成功");
        unPayedListEntity.setData(unPayedListDomain.getData());

        return unPayedListEntity;

    }

    /**
     * 获取待支付接口(健康通)
     * @param unPayedPojo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getUnpayedListExt",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<DrugDomain> getUnpayedListExt(@RequestBody UnPayedPojo unPayedPojo){
        log.info("==========  查询入参 unPayedPojo: {} ==========",unPayedPojo);
        ResponseEntity<DrugDomain>unPayedListEntity=new ResponseEntity<>();
        try {
            drugDomain = paymentService.getUnPayedListServiceExt(unPayedPojo);
            log.info("==========  查询结果 drugDomain: {} ==========",drugDomain);
        } catch (SQLException e) {
            log.error(e.getMessage());
            e.printStackTrace();
            unPayedListEntity.setCode(Constant.errorTag);
            unPayedListEntity.setMessage("数据库查询失败");
            return unPayedListEntity;
        }

        if (drugDomain.getCode()==Constant.errorTag){
            unPayedListEntity.setCode(Constant.errorTag);
            unPayedListEntity.setMessage(drugDomain.getMessage());
            return unPayedListEntity;
        }

        unPayedListEntity.setCode(Constant.successResponse);
        unPayedListEntity.setMessage("成功");
        unPayedListEntity.setData(drugDomain.getData());

        return unPayedListEntity;

    }

    @RequestMapping(value = "/getMachiningChineseHerbalMedicineCost",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<List<MachiningHerbalMedCostVo>> getMachiningChineseHerbalMedicineCost(@RequestBody FeeNoPojo feeNoPojo){

        BaseResponse<List<MS_YJ02Domain>> MS_YJ02ListResponse = paymentService.getMachiningChineseHerbalMedicineCost(feeNoPojo);

        ResponseEntity<List<MachiningHerbalMedCostVo>> entity=new ResponseEntity<>();
        List<MachiningHerbalMedCostVo> MachiningHerbalMedCostList = new ArrayList();

        if (MS_YJ02ListResponse.getCode()==Constant.errorTag){
        	entity.setCode(0);
        	entity.setMessage(MS_YJ02ListResponse.getMessage());
            return entity;
        }

        MachiningHerbalMedCostList = DozerUtils.mapList(dozerMapper,MS_YJ02ListResponse.getData(),MachiningHerbalMedCostVo.class);

//        entity.setCode(1);
//        entity.setMessage("成功");
        entity.setData(MachiningHerbalMedCostList);
        return entity;
    }

    @RequestMapping(value = "/getFeeDetail",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<Object> getFeeDetail(@RequestBody InvoiceNumberPojo invoiceNumberPojo){

        BaseResponse<FeeVoDomain> feeResponse = paymentService.getFeeDetail(invoiceNumberPojo);
//
        ResponseEntity<Object> entity=new ResponseEntity<>();
//        List<MachiningHerbalMedCostVo> MachiningHerbalMedCostList = new ArrayList();

        if (feeResponse.getCode()==Constant.errorTag){
        	entity.setCode(0);
        	entity.setMessage(feeResponse.getMessage());
            return entity;
        }

//        entity.setCode(1);
//        entity.setMessage("成功");
        entity.setData(feeResponse.getData());
        return entity;
    }
    /**
     * 4.1.3 获取费用预结算金额
     */
    @ApiOperation(value = "5003根据病人标识获取费用预结算信息",
    		notes = "入参：hospitalCode：机构id ； patientCode ：病人标识 ；takeWay：发药方式：1：到院自取2： 送药上门；"
			+ "detailedAddress：详细地址；consigneeName：姓名；consigneePhone ：手机号； boilSign：代煎标志：0：不代煎1：代煎；feeRecords：收费单据集合；"
			+ "feeNo：收费单据标识；feeTypeCode：类型代码；feeTypeName：类型名称")
    @RequestMapping(value = "/getPrecalculatedFee",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<GetPrecalculatedFeeVo> getPrecalculatedFee(@RequestBody GetPrecalculatedFeePojo getPrecalculatedFeePojo){
    	ResponseEntity<GetPrecalculatedFeeVo> entity=new ResponseEntity<>();

        try {
            BaseResponse<GetPrecalculatedFee> getPrecalculatedFee = paymentService.getPrecalculatedFee(getPrecalculatedFeePojo,0,false);

            if(getPrecalculatedFee.getCode() == Constant.errorTag || getPrecalculatedFee.getCode() == Constant.breakTag){
    //        	entity.setCode(Constant.errorTag);
                entity.setMessage(getPrecalculatedFee.getMessage());
                return entity;
            }

            GetPrecalculatedFeeVo getPrecalculatedFeeVo = new GetPrecalculatedFeeVo();
            GetPrecalculatedFee precalculatedFee = getPrecalculatedFee.getData();

            List<GetPrecalculatedFeeData2> feeDataList = new ArrayList<>();

            if (precalculatedFee.getMergingItems() != null && precalculatedFee.getMergingItems().size() > 0) {
                for (GetPrecalculatedFeeData precalculatedFeeData : precalculatedFee.getMergingItems()) {

                    GetPrecalculatedFeeData2 feeData = new GetPrecalculatedFeeData2();
                    feeData.setMergingCode(precalculatedFeeData.getMergingCode());
                    feeData.setMergingName(precalculatedFeeData.getMergingName());
                    feeData.setMergingSubtotal(precalculatedFeeData.getMergingSubtotal());

                    feeDataList.add(feeData);

                }
            }
            getPrecalculatedFeeVo.setDisplayName(precalculatedFee.getDisplayName());
            getPrecalculatedFeeVo.setExtraFeeDesc(precalculatedFee.getExtraFeeDesc());
            getPrecalculatedFeeVo.setInsuranceType(precalculatedFee.getInsuranceType());
            getPrecalculatedFeeVo.setInvoiceNumber(precalculatedFee.getInvoiceNumber());
            getPrecalculatedFeeVo.setMergingItems(feeDataList);
            getPrecalculatedFeeVo.setPayAmount(precalculatedFee.getPayAmount());
            getPrecalculatedFeeVo.setPaymentBudgetNumber(precalculatedFee.getPaymentBudgetNumber());
            getPrecalculatedFeeVo.setTotalFee(precalculatedFee.getTotalFee());


            entity.setMessage(getPrecalculatedFee.getMessage());
            entity.setData(getPrecalculatedFeeVo);
        } catch (Exception e) {
            e.printStackTrace();
            entity.setCode(Constant.errorTag);
            entity.setMessage("获取费用预结算信息失败");

        }
        return entity;
    }
    @ApiOperation(value = "获取已支付列表")
    @ResponseBody
    @RequestMapping(value = "/getPayedList",method = RequestMethod.POST,produces = "application/json")
    public ResponseEntity<List<PaymentDomain>> getPayedList(@RequestBody PaymentPojo paymentPojo){
        ResponseEntity<List<PaymentDomain>>responseEntity=new ResponseEntity<>();
        try {
            BaseResponse<List<PaymentDomain>> baseResponse= paymentService.getPatmentList(paymentPojo);
            if (baseResponse.getCode()== Constant.errorTag){
                responseEntity.setCode(Constant.errorTag);
                responseEntity.setMessage(baseResponse.getMessage());
            }else {
                responseEntity.setCode(Constant.successResponse);
                responseEntity.setMessage(baseResponse.getMessage());
                responseEntity.setData(baseResponse.getData());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return responseEntity;
    }
    
	/**
	 * 4.1.4确认费用结算处理
	 */
	@ApiOperation(value = "5004互联网医院支付成功后，调用该接口通知HIS进行结算", notes = "入参：hospitalCode：机构id ； patientCode ：病人标识 ；invoiceNumber：发票号码；payMode：支付方式：1-支付宝/2-微信/3-银联；"
			+ "payState：支付标志；agtOrderNumber ：对应收单机构金额； payAmount：付款金额；outOrderNumber：商户订单号；channelOrderNumber:渠道商订单号"
			+ "notify：支付成功时的通知信息；paymentBudgetNumber：预结算标识；payTime：实际支付时间；tradeType：服务项目代码：固定值：0108；payer：付款人；"
			+ "selfPay：自付金额；feeRecords： ；feeNo：收费单据标识；feeTypeCode：类型代码；feeTypeName:类型名称")
	@RequestMapping(value = "/notifyPayed", method = RequestMethod.POST, produces = "application/json")
	public ResponseEntity<NotifyPayed> notifyPayed(@RequestBody NotifyPayedPojo notifyPayedPojo) {
		ResponseEntity<NotifyPayed> entity = new ResponseEntity<>();
        try{
            List<UnPayedListDomain> unPayedListDomainData = unPayedListDomain.getData();
            BaseResponse<NotifyPayed> notifyPayed = paymentService.notifyPayed(notifyPayedPojo,unPayedListDomainData);

    //		entity.setCode(notifyPayed.getCode());

             if(notifyPayed.getCode() == Constant.errorTag){
                entity.setCode(Constant.errorTag);
            }

            entity.setMessage(notifyPayed.getMessage());
		    entity.setData(notifyPayed.getData());
//		if(notifyPayed.getData() != null){
//			entity.setData(notifyPayed.getData());
//		}
        } catch (Exception e) {
            e.printStackTrace();
            entity.setCode(Constant.errorTag);
            entity.setMessage("费用结算失败");

        }

		return entity;
	}

    /**
     * 4.1.4确认费用结算处理
     */
    @ApiOperation(value = "5004互联网医院支付成功后，调用该接口通知HIS进行结算", notes = "入参：hospitalCode：机构id ； patientCode ：病人标识 ；invoiceNumber：发票号码；payMode：支付方式：1-支付宝/2-微信/3-银联；"
            + "payState：支付标志；agtOrderNumber ：对应收单机构金额； payAmount：付款金额；outOrderNumber：商户订单号；channelOrderNumber:渠道商订单号"
            + "notify：支付成功时的通知信息；paymentBudgetNumber：预结算标识；payTime：实际支付时间；tradeType：服务项目代码：固定值：0108；payer：付款人；"
            + "selfPay：自付金额；feeRecords： ；feeNo：收费单据标识；feeTypeCode：类型代码；feeTypeName:类型名称")
    @RequestMapping(value = "/jktNotifyPayed", method = RequestMethod.POST, produces = "application/json")
    public ResponseEntity<NotifyPayed> jktNotifyPayed(@RequestBody NotifyPayedPojo notifyPayedPojo) {
        ResponseEntity<NotifyPayed> entity = new ResponseEntity<>();
        try{
            BaseResponse<NotifyPayed> notifyPayed = paymentService.jktNotifyPayed(notifyPayedPojo);

            //		entity.setCode(notifyPayed.getCode());

            if(notifyPayed.getCode() == Constant.errorTag){
                entity.setCode(Constant.errorTag);
            }

            entity.setMessage(notifyPayed.getMessage());
            entity.setData(notifyPayed.getData());
		if(notifyPayed.getData() != null){
			entity.setData(notifyPayed.getData());
		}
        } catch (Exception e) {
            e.printStackTrace();
            entity.setCode(Constant.errorTag);
            entity.setMessage("费用结算失败");

        }

        return entity;
    }
	
	/**
	 * 4.1.5支付公用
	 */
	@ApiOperation(value = "5008支付公用：获取商户订单号。", notes = "入参：hospitalCode：机构id ； busType ：业务类别 ；payMode：支付方式；"
			+ "amount：订单金额；patientCode ：病人ID； patientIdentityCardType：证件类型；patientIdentityCardNumber：证件号码；")
	@RequestMapping(value = "/createOrderNo", method = RequestMethod.POST, produces = "application/json")
	public ResponseEntity<CreateOrserNoDomain> getShddh(@RequestBody CreateOrderNoPojo createOrderNoPojo) {
		ResponseEntity<CreateOrserNoDomain> entity = new ResponseEntity<>();

		BaseResponse<CreateOrserNoDomain> baseResponse = createOrderNoService.getShddh(createOrderNoPojo);
		
		 if(baseResponse.getCode() == Constant.errorTag){
	        	entity.setCode(Constant.errorTag);
	        }
//		entity.setCode(baseResponse.getCode());
		entity.setMessage(baseResponse.getMessage());
		entity.setData(baseResponse.getData());
//		if(notifyPayed.getData() != null){
//			entity.setData(notifyPayed.getData());
//		}
		

		return entity;
	}

    @RequestMapping(value = "/getInvoiceList", method = RequestMethod.POST, produces = "application/json")
	public ResponseEntity<List<InvoiceDomain>> getInvoiceList(@RequestBody InvoiceParam invoiceParam){
        ResponseEntity<List<InvoiceDomain>> responseEntity = new ResponseEntity<>();
	    if(StringUtils.isBlank(invoiceParam.getIdCard())){
            responseEntity.setCode(-100);
            responseEntity.setMessage("身份证号码不能为空！");
        }
        BaseResponse<List<InvoiceDomain>> invoiceList = patientService.getInvoiceList(invoiceParam.getIdCard());
        responseEntity.setCode(200);
        responseEntity.setData(invoiceList.getData());
        return responseEntity;
    }
}
